import 'dart:async';
import "package:flutter/material.dart";
import 'package:flutter_pink_app/composables/listbottom_loading.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../composables/feed_list.dart';
import '../business/get_home_category.dart';
import '../serialized/recommend.dart';

// 详情页组件
class DetailPage extends StatefulWidget {
  DetailPage(this.category);
  final CategoryInfo category; // 请求种类字段

  @override
  _DetailPageState createState() => _DetailPageState();
}

class _DetailPageState extends State<DetailPage>
    with AutomaticKeepAliveClientMixin<DetailPage> {
  final int _loadAmount = 20; // 一次性加载数量
  int _totalAmount = 0;
  List<VideoInfo> _videoList = []; // 播放视频页数据
  int _requestPage = 1; // 请求页数
  bool _isLoading = false; // 是否正在加载中

  // 生命周期初始化
  @override
  void initState() {
    super.initState();
    _initRequest();
    _totalAmount = widget.category.count; // 初始化总加载数量
    Fluttertoast.showToast(
        msg: "已刷新$_totalAmount条数据", 
        gravity: ToastGravity.TOP);
  }

  @override
  void dispose() {
    super.dispose();
    super.deactivate(); // 废除缓存
  }

  @override
  bool get wantKeepAlive => true;

  // 更新请求信息数量
  void _updatePageIndex() {
    _requestPage++;
  }

  // 更新加载状态
  void _updateLoadingStatus(bool value) {
    setState(() {
      _isLoading = value;
    });
  }

  // 初始化时请求数据
  void _initRequest() async {
    final res = await getHomeCategory(widget.category.name,
        amount: _loadAmount, pageIndex: _requestPage); // 初始化时加载数据
    // 请求失败时5秒后发起轮循
    if (res == null) {
      Timer(Duration(seconds: 5), _initRequest);
      return;
    }
    final videoList = res.videoList;
    // 如果页面仍存在则挂载数据
    if (mounted) {
      setState(() {
        assert(videoList.length > 0, '返回的影音数据列表不应为空');
        _videoList = videoList;
        _updatePageIndex();
      });
    }
  }

  // 请求更多影像数据，传给子级
  void _loadMoreVideo() async {
    print('loadMoreVideo at DetailPage');
    _updateLoadingStatus(true);
    final res = await getHomeCategory(widget.category.name,
        amount: _loadAmount, pageIndex: _requestPage); // 更多数据
    _updateLoadingStatus(false);
    // 请求失败时处理
    if (res == null) {
      return;
    }
    // 请求到数据后如果当前页面仍存在且仍有数据即刷新原始数据
    if (mounted && res.videoList != null) {
      final videoList = res.videoList;
      setState(() {
        _videoList.addAll(videoList);
      });
      _updatePageIndex();
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Stack(
      children: [
        Feed2DList(_videoList, refreshCallback: _loadMoreVideo),
        Positioned(
            bottom: 0,
            left: 0,
            right: 0,
            child: ListBottomLoading(
              isOff: !_isLoading,
              loadingText: _videoList.length == _totalAmount
                  ? "再怎么刷新也没用啦 TAT "
                  : "~ 正在努力加载中 QAQ ~",
            ))
      ],
    );
  }
}
